package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UsersService {

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;

    public UserInfoVo queryUserInfo(String userID, String huanxinID) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        if (StringUtils.isNotBlank(userID)) {
            userId = Long.valueOf(userID);
        } else if (StringUtils.isNotBlank(huanxinID)) {
            userId = Long.valueOf(huanxinID);
        }
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        if (null == userInfo) {
            return null;
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setAge(userInfo.getAge() != null ? userInfo.getAge().toString() : null);
        userInfoVo.setAvatar(userInfo.getLogo());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setEducation(userInfo.getEdu());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setIncome(userInfo.getIncome() + "K");
        userInfoVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setProfession(userInfo.getIndustry());

        return userInfoVo;
    }

    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    public CountsVo queryCounts() {
        Long userId = UserThreadLocal.get().getId();
        Long count1 = userLikeApi.queryEachLikeCount(userId);
        Long count2 = userLikeApi.queryLikeCount(userId);
        Long count3 = userLikeApi.queryFanCount(userId);
        CountsVo countsVo = new CountsVo(count1, count2, count3);
        return countsVo;
    }

    //1 互相关注 2 我关注 3 粉丝 4 谁看过我
    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) {
        Long userId = UserThreadLocal.get().getId();
        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        Set<Long> userIds = new HashSet<>();
        if (type == 1) {
            PageInfo<UserLike> pageInfo = userLikeApi.queryEachLikeList(userId, page, pageSize);
            for (UserLike userLike : pageInfo.getRecords()) {
                userIds.add(userLike.getUserId());
            }
        } else if (type == 2) {
            PageInfo<UserLike> pageInfo = userLikeApi.queryLikeList(userId, page, pageSize);
            for (UserLike userLike : pageInfo.getRecords()) {
                userIds.add(userLike.getLikeUserId());
            }
        } else if (type == 3) {
            PageInfo<UserLike> pageInfo = userLikeApi.queryFanList(userId, page, pageSize);
            for (UserLike userLike : pageInfo.getRecords()) {
                userIds.add(userLike.getUserId());
            }
        } else if (type == 4) {
            List<Visitors> visitors = visitorsApi.topVisitor(userId, page, pageSize);
            for (Visitors visitor : visitors) {
                userIds.add(visitor.getVisitorUserId());
            }
            String redisKey = "visitors_" + userId;
            redisTemplate.opsForValue().set(redisKey, String.valueOf(System.currentTimeMillis()));
        }
        if (CollectionUtils.isEmpty(userIds)) {
            return pageResult;
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.isNotBlank(nickname)) {
            queryWrapper.like("nick_name", nickname);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());

            Double score = this.recommendUserService.queryScore(userId, userInfo.getUserId());
            if (score == 0) {
                score = RandomUtils.nextDouble(30, 90);
            }
            userLikeListVo.setMatchRate(score.intValue());

            userLikeListVos.add(userLikeListVo);
        }
        pageResult.setItems(userLikeListVos);
        return pageResult;
    }

    public void disLike(Long userId) {
        userLikeApi.deleteUserLike(UserThreadLocal.get().getId(), userId);
        //TODO
    }

    public void likeFan(Long userId) {
        userLikeApi.saveUserLike(UserThreadLocal.get().getId(), userId);
        //TODO
    }

    public SettingsVo querySettings() {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        SettingsVo settingsVo = new SettingsVo(userId, user.getMobile());
        Settings settings = settingsService.querySettings(userId);
        if (null != settings) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }
        Question question = questionService.queryQuestion(userId);
        String txt = question.getTxt();
        if (StringUtils.isNotBlank(txt)) {
            settingsVo.setStrangerQuestion(txt);
        }
        return settingsVo;
    }

    public void saveQuestions(String content) {
        questionService.save(UserThreadLocal.get().getId(), content);
    }

    public PageResult queryBlacklist(Integer page, Integer pagesize) {
        IPage<BlackList> blackListIPage = blackListService.queryBlacklist(UserThreadLocal.get().getId(), page, pagesize);
        PageResult pageResult = new PageResult(new Long(blackListIPage.getTotal()).intValue(),pagesize,new Long(blackListIPage.getPages()).intValue(),page);
        List<BlackList> records = blackListIPage.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }
        HashSet<Long> blackUserIds=new HashSet<>();
        for (BlackList blackList : records) {
            blackUserIds.add(blackList.getBlackUserId());
        }
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper();
        queryWrapper.in("user_id", blackUserIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        List<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    public void delBlacklist(Long userId) {
        blackListService.delBlacklist(UserThreadLocal.get().getId(), userId);
    }

    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        settingsService.updateNotification(UserThreadLocal.get().getId(), likeNotification, pinglunNotification, gonggaoNotification);
    }
}
